<template>
    <div class="sampling-add-form">
        <div class="section">
            <h2 class="section-title">抽检基本信息</h2>
            <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="samp_order" status-icon
                :rules="rules" label-width="auto" class="demo-ruleForm">
                <el-form-item label="抽检单号" prop="samp_code">
                    <el-input v-model="samp_order.samp_code" placeholder="不输入则自动获取编号" />
                </el-form-item>

                <div class="form-columns">
                    <div class="form-column">
                        <el-form-item label="抽检类型" prop="samp_type" style="margin-bottom: 30px;">
                            <el-select v-model="samp_order.samp_type" placeholder="请选择抽检类型">
                                <el-option v-for="item in samplingTypes" :key="item.dict_value" :label="item.dict_label"
                                    :value="item.dict_value" class="option-style" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="抽检仓库" prop="warehouse_code" style="margin-bottom: 30px;">
                            <el-select v-model="samp_order.warehouse_code" placeholder="请选择抽检仓库"
                                @change="handleWarehouseChange">
                                <el-option v-for="item in warehouses" :key="item.warehouse_code"
                                    :label="item.warehouse_name" :value="item.warehouse_code" />
                            </el-select>
                        </el-form-item>
                    </div>

                    <div class="form-column">
                        <el-form-item label="抽检日期" prop="samp_startdate" style="margin-bottom: 30px;">
                            <el-date-picker v-model="samp_order.samp_startdate" type="datetime" placeholder="选择日期时间"
                                style="width: 100%;" />
                        </el-form-item>

                        <el-form-item label="抽检员" prop="samp_inspector" style="margin-bottom: 30px;">
                            <el-input v-model="samp_order.samp_inspector" placeholder="请输入抽检人" />
                        </el-form-item>

                        
                    </div>
                </div>
            </el-form>
        </div>

        <div class="section">
            <h2 class="section-title">抽检产品明细</h2>
            <div class="product-actions">
                <el-button type="primary" @click="productAdd">添加产品</el-button>
                <el-button @click="productDel">移除选中</el-button>
            </div>

            <el-table :data="selectedData" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                textAlign: 'center',
                background: '#f5f7fa',
                fontWeight: 'bold',
                position: 'sticky',
                top: 0
            }" ref="selectedTable" @selection-change="handleSelectedChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="stock_name" label="货品名称" fixed="left" width="140" />
                <el-table-column prop="pro_code" label="货品编号" width="150" />
                <el-table-column prop="pro_brand" label="品牌" width="140" />
                <el-table-column prop="stock_model" label="规格型号" width="140" />
                <el-table-column label="单位" width="120">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.dict_code) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="stock_numder" label="当前库存" width="100" />
                <el-table-column label="抽检数量" width="120">
                    <template #default="scope">
                        <el-input v-model="scope.row.samp_numder" style="width: 75px" :min="0"
                            :max="scope.row.stock_numder" />
                    </template>
                </el-table-column>
                <el-table-column label="合格数量" width="140">
                    <template #default="scope">
                        <el-input v-model="scope.row.prodInfo_totnum_qify" style="width: 75px"
                            :max="scope.row.samp_numder" @input="calcResult(scope.row)" />
                    </template>
                </el-table-column>
                <el-table-column label="不合格数量" width="120">
                    <template #default="scope">
                        <span>{{ (scope.row.samp_numder || 0) - (scope.row.prodInfo_totnum_qify || 0) }}</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="抽检结果" width="130">
                    <template #default="scope">
                        <el-select v-model="scope.row.prodInfo_Sampling_results" placeholder="结果" :disabled="true">
                       
                            <el-option label="合格" value="1" />
                            <el-option label="不合格" value="2" />
                            <el-option label="部分合格" value="3" />
                            <el-option label="严重缺陷" value="4" />
                        </el-select>
                    </template>
                </el-table-column> -->
            </el-table>

            <div class="summary-row">
                <span>合计</span>
                <div class="summary-values">
                    <span>抽检总数量：{{ sampling_total_qty }}</span>
                    <span>合格总数：{{ qualified_total_qty }}</span>
                    <span>不合格总数：{{ unqualified_total_qty }}</span>
                </div>
            </div>
        </div>

        <div class="button-group">
            <el-button type="primary" @click="handleAdd">保存</el-button>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>

    <!--产品模态框-->
    <el-dialog v-model="dialogTableVisible" width="800" title="添加产品">
        <hr>
        <div class="product-filter">
            <el-input v-model="productcode" placeholder="请输入货品编号" style="width: 240px; margin-right: 20px;" />
            <el-select v-model="dict_code" placeholder="请选择单位" style="width: 240px">
                <el-option v-for="item in measureOptios" :key="item.dict_value" :label="item.dict_label"
                    :value="item.dict_value" />
            </el-select>
            <el-button @click="productReset">重置</el-button>
            <el-button type="primary" @click="productSearch">查询</el-button>
        </div>

        <el-table ref="multipleTableRef" :data="productData" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
                textAlign: 'center',
                background: '#f5f7fa',
                fontWeight: 'bold',
                position: 'sticky',
                top: 0
            }" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" :selectable="isProductSelectable" />
            <el-table-column property="pro_code" label="货品编号" width="180" />
            <el-table-column property="stock_name" label="货品名称" width="200" />
            <el-table-column property="stock_model" label="规格型号" />
            <el-table-column label="单位">
                <template #default="scope">
                    <span>{{ measureValue(scope.row.dict_code) }}</span>
                </template>
            </el-table-column>
            <el-table-column property="pro_cost_price" label="成本价" />
            <el-table-column property="pro_sale_price" label="销售价" />
            <el-table-column property="stock_numder" label="当前库存" />
        </el-table>

        <div class="pagination">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
                :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogTableVisible = false">取消</el-button>
                <el-button type="primary" @click="handleConfirmSelection">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const router = useRouter();

const samplingTypes = ref([])
const warehouses = ref([]);

let sampAdd = {
    samp_type: "",
    samp_code: "",
    samp_inspector: localStorage.getItem('userLName'),
    samp_startdate: "",
    warehouse_code: "",
    warehouse_name: "",
    samp_results: "",
    //samp_is_stored: "1",
    samp_audit_by: "",
    del_flag: '0',
    create_by: localStorage.getItem('userLName'),
    create_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
    samp_outbound:'0',//0:未出库 1:已出库
}

const samp_order = reactive({ ...sampAdd })

const ruleFormRef = ref(null)
const rules = reactive({
    warehouse_code: [{ required: true, message: '请选择抽检仓库', trigger: 'change' }],
    samp_type: [{ required: true, message: '请选择抽检类型', trigger: 'change' }],
    samp_startdate: [{ required: true, message: '请选择抽检日期', trigger: 'change' }],
    samp_inspector: [{ required: true, message: '请输入抽检人', trigger: 'blur' }]
});

// 是否显示“添加产品”弹出框（模态框）
const dialogTableVisible = ref(false)

// 从接口获取的【可选产品列表】（仓库库存中的产品）
const productData = ref([])

// 当前分页的页码（用于产品列表）
const currentPage = ref(1)


// 每页显示多少条产品数据
const pageSize = ref(5)

// 产品总条数（用于分页组件计算总页数）
const pageCount = ref(0)

// 搜索框：按产品名称或编号过滤
const productcode = ref("")

// 搜索框：按计量单位过滤（"0" 表示不限制）
const dict_code = ref("0")

// 所有“计量单位”字典项（如：件、箱、kg 等）
const measureOptios = ref([])

// 指向“产品选择表格”的 DOM 引用，用于清空/控制选中状态
const multipleTableRef = ref(null)

// 在弹出框中临时选中的产品（未点击“确定”前）
const selectedProducts = ref([])

// 指向“已选产品明细表格”的 DOM 引用
const selectedTable = ref(null)

// 用户在“已选产品明细表格”里勾选的行
const selectedRows = ref([])

// 最终确认添加到抽检单的产品列表（页面下方表格）
const selectedData = ref([])

// 抽检单中所有产品的“抽检总数量”合计
const sampling_total_qty = ref(0)

// 抽检单中所有产品的“合格总数量”合计
const qualified_total_qty = ref(0)

// 抽检单中所有产品的“不合格总数量”合计
const unqualified_total_qty = ref(0)



//事件监听
watch(selectedData, (newVal) => {
    sampling_total_qty.value = 0
    qualified_total_qty.value = 0
    unqualified_total_qty.value = 0

    newVal.forEach(row => {
        if (isNaN(Number(row.samp_numder))) {
            ElMessage.warning('抽检数量必须是数字');
            row.samp_numder = 0;
        }
        if (isNaN(Number(row.prodInfo_totnum_qify))) {
            ElMessage.warning('合格数量必须是数字');
            row.prodInfo_totnum_qify = 0;
        }

        if (row.samp_numder > row.stock_numder) {
            ElMessage.warning(`${row.stock_name}的抽检数量不能大于当前库存`);
            row.samp_numder = row.stock_numder
        }

        if (row.prodInfo_totnum_qify > row.samp_numder) {
            ElMessage.warning(`${row.stock_name}的合格数量不能大于抽检数量`)
            row.prodInfo_totnum_qify = row.samp_numder
        }



        sampling_total_qty.value += Number(row.samp_numder || 0)
        qualified_total_qty.value += Number(row.prodInfo_totnum_qify || 0)
        unqualified_total_qty.value += (Number(row.samp_numder || 0) - Number(row.prodInfo_totnum_qify || 0))        
    });
}, { deep: true });

const handleWarehouseChange = (selectedValue) => {
    const selectedItem = warehouses.value.find(item => item.warehouse_code === selectedValue);
    samp_order.warehouse_name = selectedItem?.warehouse_name || "";
};
//点击添加产品
const productAdd = () => {
    if (!samp_order.warehouse_code) {
        ElMessage.warning('请先选择抽检仓库');
        return;
    }
    dialogTableVisible.value = true;
    //产品数据
    productFill();
    //统计数据
    productCount();
};
//数据移出
const productDel = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要移除的数据');
        return;
    }

    // 创建一个包含选中项的 stock_entry_no 和 pro_code 的数组
    const selectedEntries = selectedRows.value.map(item => ({
        stock_entry_no: item.stock_entry_no,
        pro_code: item.pro_code
    }));

    // 过滤掉被选中的项
    selectedData.value = selectedData.value.filter(item => {
        // 检查当前项的 stock_entry_no 和 pro_code 是否不在选中的数组中
        return !selectedEntries.some(
            selected =>
                selected.stock_entry_no === item.stock_entry_no &&
                selected.pro_code === item.pro_code
        );
    });

    if (selectedTable.value) {
        selectedTable.value.clearSelection();
    }
    selectedRows.value = [];
};

//响应判断逻辑--结果
function calcResult() {
    const total = sampling_total_qty.value;
    const qualify = qualified_total_qty.value;

    if (qualify === total) {
        samp_order.samp_results = '1'; // 全部合格
    } else if (qualify === 0) {
        samp_order.samp_results = '2'; // 全部不合格
    } else if (qualify > 0 && qualify < total) {
        samp_order.samp_results = '3'; // 部分合格
    } else {
        samp_order.samp_results = '1'; // 兜底
    }
}

const productFill = () => {
    axios.get("http://localhost:5181/api/Inv_Stock/Get_Select_stock_All", {
        params: {
            weahouse_code: samp_order.warehouse_code,
            pro_code: productcode.value,
            dict_code: dict_code.value,
            currentPage: currentPage.value,
            pageSize: pageSize.value
        },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then((result) => {
        productData.value = result.data || []
    }).catch((err) => {
        console.error(err);
        ElMessage.error('获取产品数据失败');
    });
};

const productCount = () => {
    axios.get("http://localhost:5181/api/Inv_Stock/Get_Select__stock_Count", {
        params: {
            weahouse_code: samp_order.warehouse_code,
            pro_code: productcode.value,
            dict_code: dict_code.value,
        },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then((result) => {
        pageCount.value = result.data || 0
    }).catch((err) => {
        console.error(err);
    });
};

const handleSizeChange = (val) => {
    pageSize.value = val;
    productFill();
};

const handleCurrentChange = (val) => {
    currentPage.value = val;
    productFill();
};
// 获取抽检类型
const getSamplingTypes = () => {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: { dict_type: "inv_samp" },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then((result) => {
        samplingTypes.value = result.data || [];
    }).catch((err) => {
        console.error(err);
    });
};

const getWarehouses = () => {
    axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect", {
        headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') }
    }).then((res) => {
        warehouses.value = res.data || [];
    }).catch((res) => {
        console.log(res);
    });
};

const getMeasure = () => {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: { dict_type: "db_measure" },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then((result) => {
        measureOptios.value = [{ dict_value: "0", dict_label: "请选择单位" }, ...(result.data || [])];
    }).catch((err) => {
        console.error(err);
    });
};

const measureValue = (row) => {
    if (!row) return "无";
    const unit = measureOptios.value.find((item) => item.dict_value == row);
    return unit ? unit.dict_label : "无";
};

const productSearch = () => {
    productFill();
    productCount();
};

const productReset = () => {
    productcode.value = "";
    dict_code.value = "0";
    productFill();
    productCount();
};

const handleSelectionChange = (val) => {
    selectedProducts.value = val;
};

const handleConfirmSelection = () => {
    selectedData.value = [
        ...selectedData.value,
        ...selectedProducts.value.map(item => ({
            ...item,
            samp_numder: 0,
            prodInfo_totnum_qify: 0,
            prodInfo_Sampling_results: "1"
        }))
    ];

    dialogTableVisible.value = false;
    if (multipleTableRef.value) {
        multipleTableRef.value.clearSelection();
    }
};

const handleSelectedChange = (val) => {
    selectedRows.value = val;
};
//
const isProductSelectable = (row) => {
    return !selectedData.value.some(
        item => item.pro_code === row.pro_code && item.stock_entry_no === row.stock_entry_no
    );
};
// 点击确定存储选择的产品数据
const handleAdd = async () => {
    try {
        const valid = await ruleFormRef.value.validate().catch(() => false);
        if (!valid) {
            ElMessage.warning('请先完善必填项');
            return;
        }

       

        if (selectedData.value.length === 0) {
            ElMessage.warning('请添加抽检产品');
            return;
        }
        //判断抽检接口
        calcResult();

        await obtainCode();

        const mainResponse = await axios.put(
            "http://localhost:5181/api/Inv_Samp/Inv_Samp_Insert",
            samp_order,
            { headers: { authorization: `Bearer ${localStorage.getItem('token')}` } }
        );

        if (mainResponse.data > 0) {
            // 添加主表成功,获取新增的ID
            const sampId = await Select_samp_id();

            const detailList = selectedData.value.map(item => ({
               
                samp_id: sampId,
                pro_name: item.stock_name,
                pro_code: item.pro_code,
                pro_brand: item.pro_brand,
                pro_model: item.stock_model,
                unitmeas_id: String(item.dict_code),
                samp_numder: item.samp_numder,
                prodInfo_totnum_qify: item.prodInfo_totnum_qify,
                prodInfo_totnum_uqual: (item.samp_numder || 0) - (item.prodInfo_totnum_qify || 0),
                prodInfo_Sampling_results: item.prodInfo_Sampling_results,
                warehouse_code: samp_order.warehouse_code,
                stock_entry_no: item.stock_entry_no,
            }));

            const detailList1 = selectedData.value.map(item => ({
                pro_name: item.stock_name,
                pro_code: item.pro_code,
                pro_brand: item.pro_brand,
                pro_model: item.stock_model,
                unitmeas_id: String(item.dict_code),
                samp_numder: item.samp_numder,
                prodInfo_totnum_qify: item.prodInfo_totnum_qify,
                prodInfo_totnum_uqual: (item.samp_numder || 0) - (item.prodInfo_totnum_qify || 0),
                prodInfo_Sampling_results: item.prodInfo_Sampling_results,
                warehouse_code: samp_order.warehouse_code,
                stock_entry_no: item.stock_entry_no,
            }));
            //console.log(detailList);
            //添加盘点详细表
            await saveSamplingDetails(detailList);
            //修改库存的不合格单
            //stock_Update_stockUnqualified_numder(detailList1);

            ElMessage.success('抽检单创建成功');

            Object.assign(samp_order, sampAdd);
            selectedData.value = [];

            router.push('/main/Inv/InvSamp');
        } else {
            ElMessage.error("主表保存失败");
        }
    } catch (error) {
        console.error("保存出错:", error);
        ElMessage.error("保存过程中发生错误");
    }
};

//修改库存里面的抽检不合格数量
function stock_Update_stockUnqualified_numder(detailList){
    axios.put("http://localhost:5181/api/Inv_Stock/Stock_Update_stockUnqualified_numder", detailList,{
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then(res => { 
        if (res.data > 0) { 
            console.log("库存修改成功");
        }else { 
            console.log("库存修改失败");
        }
    }).catch(err => { 
        console.error(err);
    });
}

// 查询抽样单id
const Select_samp_id = async () => {
    const response = await axios.get(
        "http://localhost:5181/api/Inv_Samp/Inv_sampt_selectId",
        {
            params: { samp_code: samp_order.samp_code },
            headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        }
    );
    return response.data;
};
// 保存盘点单详情
const saveSamplingDetails = (detailList) => {
    return axios.put(
        "http://localhost:5181/api/Inv_Samp/Inv_prodInfo_Insert",
        detailList,
        { headers: { authorization: `Bearer ${localStorage.getItem('token')}` } }
    );
};
// 生成单号
const obtainCode = async () => {
    try {
        const result = await axios.get("http://localhost:5181/api/DJBH/DJBH", {
            params: { en_code: 19 },
            headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        samp_order.samp_code = result.data;
    } catch (err) {
        console.error("生成单号失败:", err);
        throw err;
    }
};

const handleClose = () => {
    router.push('/main/Inv/InvSamp');
};

onMounted(() => {
    getSamplingTypes();
    getMeasure();
    getWarehouses();
});
</script>

<style scoped>
.sampling-add-form {
    padding: 20px;
    background-color: #fff;
    position: relative;
    min-height: 100vh;
}

.section {
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
    color: #333;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
}

.form-columns {
    display: flex;
    justify-content: space-between;
    gap: 20px;
}

.form-column {
    flex: 1;
}

.product-actions {
    margin-bottom: 15px;
    display: flex;
}

.summary-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    line-height: 40px;
    padding: 0 10px;
    border-top: none;
    margin-top: -1px;
}

.summary-values {
    display: flex;
    gap: 20px;
    font-weight: bold;
}

.summary-values span {
    padding: 2px 10px;
    border-radius: 4px;
}

.button-group {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #eee;
}

.product-filter {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    gap: 10px;
}

.pagination {
    display: flex;
    justify-content: center;
    margin: 15px 0;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    padding-top: 15px;
    border-top: 1px solid #ebeef5;
}

.el-table--enable-row-hover .el-table__body tr:hover>td {
    background-color: #f5f7fa !important;
    cursor: pointer;
}
</style>